thin.imports('/public/home/css/global.project.css');

thin.imports('/public/configure/conf.project.js');
thin.imports('/public/home/resource/compress.js');

thin.use(function() {

	// 路由
	checkLocation();

	// 绑定压缩上传图片按钮
	$('[layout-mark=uploadFile]').on('change', thin.uploadImage);

	// 绑定上传商业计划书按钮
	$('#uploadfile-pdf').on('change', function(e) {
		var src,
			url = window.URL || window.webkitURL || window.mozURL,
			files = e.target.files;
		if(!files[0]) return null;
		if(url) {
			src = url.createObjectURL(files[0]);
		} else {
			src = e.target.result;
		}
		var u = $(this).attr('data-u');
		window[u].get($(this), files[0].name);
		var fileInput = this.files[0];
		var form = new FormData();
		form.append("file", fileInput);
		form.append("name", "file");
		form.append("document", "pdf");
		form.append("dir", 'upload');
		ajax().upload('/api?common.upload', form, window[u]);
		this.parentNode.reset();
	});

	$('#uploaderFiles').on('click', 'li', function(e) {
		var _id = $(this).attr('data-id');
		$('#galleryImgDelete').attr('data-id', _id);
		$('#gallery').children('#galleryImg').attr("style", this.getAttribute("style"));
		$('#gallery').fadeIn(100);
	});

	$('#gallery').on("click", function() {
		$(this).fadeOut(100);
	});

	$('#galleryImgDelete').on('click', function(e) {
		var e = e || window.event;
		e.stopPropagation();
		$('#gallery').trigger('click');
		var _id = $(this).attr('data-id');
		$('.weui-uploader__file[data-id=' + _id + ']').remove();
		delete atlasopt[_id];
	});

	$('[layout-mark=autoarea]').keyup(function(e) {
		var e = e || window.event;
		var html = this.value;
		var count = 1;
		html.replace(/\n/g, function(w) {
			count++;
		});
		var h = count * 24;
		(h < 120) && (h = 120);
		this.style.height = h + "px";
	});

	$('#btn-uploadfile-pdf').on('click', function() {
		var u = navigator.userAgent;
		var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
		//var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		if(isAndroid) {
			// 安卓用户
			document.getElementById('uploadfile-pdf').click();
		} else {
			// iOS用户
			$.alert("请使用电脑登录账号上传商业计划书", "提示");
		}
	});

	$('#btn-select-pdf').on('click', function(e) {
		var e = e || window.event;
		e.stopPropagation();
		e.preventDefault();
		var title = $('input[name=iptpdf]:checked').attr('data-title');
		data_bp = $('input[name=iptpdf]:checked').val();
		$('#btn-selbp').find('.value-text').html(title);
		//$('[data-target=#popup-upload-pdf]').find('.value-text').html(val);
		$.closePopup();
	});

	$('#perfect-template').on('click', 'a[layout-mark=btn-action-sheet]', function(e) {
		var e = e || window.event;
		e.stopPropagation();
		e.preventDefault();
		var that = $(this);
		$.actions({
			actions: [{
				text: "编辑",
				className: '',
				onClick: function() {
					var data_json = that.find('textarea').val(),
						name = that.find('p').text();
					data_json = JSON.parse(data_json);
					var info = JSON.parse(data_json.info);
					$('#ipt-p-name').val(name);
					$('#people-info').find('a').each(function(index) {
						var n = $(this).attr('data-name');
						$(this).find('.value-text').html(info[n]);
					});
					nowElemt = that;
					$('#btn-addpeople').attr('data-cmd', 'edit');
					$('#popup-people').popup();
				}
			}, {
				text: "删除",
				className: '',
				onClick: function() {
					submitPerfectProject(false);
					that.remove();
				}
			}]
		});
	});

	$('#btn-isreg').on('click', function(e) {
		var checked = $(this).prop('checked');
		if(checked === true) {
			$('#isreg-company').show();
		} else {
			$('#isreg-company').hide();
		}
	});

	$('[layout-mark=sheet-select]').on('click', function(e) {
		var e = e || window.event;
		e.stopPropagation();
		e.preventDefault();
		var itor = $(this).attr('data-itor');
		$(itor).children('.weui-mask').css({
			'opacity': 1,
			'visibility': 'visible'
		});
		$(itor).fadeIn(200);
		return false;
	});

	$('.weui-skin_android').each(function(index) {
		var that = $(this),
			_id = that.attr('id');
		that.children('.weui-mask').on('click', function(e) {
			var e = e || window.event;
			e.stopPropagation();
			e.preventDefault();
			that.fadeOut(200);
		});
		that.find('.weui-actionsheet__cell').on('click', function(e) {
			var e = e || window.event;
			e.stopPropagation();
			e.preventDefault();
			that.fadeOut(200);
			var val = $(this).html();
			$('[data-itor=#' + _id + ']').find('.value-text').html(val);
		});
	});

	$('#submit-create').on('click', submitCreateProject);

	$('#submit-perfect').on('click', submitPerfectProject);

	$('#btn-addpeople').on('click', addPeople);

	$('#btn-respeople').on('click', resPeople);

	$('#btn-selbp').on('click', function() {
		//showSelbp
		var uri = $(this).attr('data-uri');
		if(uri && uri != '') {
			window.location.href = uri;
			/*$.modal({
				title: "提示",
				text: "已上传商业计划书",
				buttons: [{
						text: "查看",
						onClick: function() {
							window.location.href = uri;
						}
					},
					{
						text: "重新上传",
						className: "default",
						onClick: function() {
							$('#btn-uploadfile-pdf').trigger('click');
						}
					},
				]
			});*/
		} else {
			$.alert("未上传商业计划书", "提示");
		}
	});
});

/*function showSelbp() {
	if(!jude_selbp) {
		$.showLoading();
		factory.request('_bp_volist');
		jude_selbp = true;
	} else {
		$('#popup-upload-pdf').popup();
	}
}

function __complete_bpvolist(res) {
	$.hideLoading();
	if(res.status == 200) {
		createBpv(res.data);
	} else {
		$.toptip(res.error, 'error');
	}
}

function createBpv(data) {
	var ele = '';
	for(var i in data) {
		ele += createBpvNode(data[i]);
	}
	$('#bpvlist').html(ele);
	$('#popup-upload-pdf').popup();
}

function createBpvNode(data) {
	var ele = '';
	ele += '<label class="weui-cell weui-check__label" for="bpvl' + data.id + '">';
	ele += '<div class="weui-cell__bd">';
	ele += '<p>' + data.title + '</p>';
	ele += '</div>';
	ele += '<div class="weui-cell__ft">';
	ele += '<input type="radio" class="weui-check" name="iptpdf" id="bpvl' + data.id + '" value="' + data.bp_uri + '" data-title="' + data.title + '" ' + (data.checked ? 'checked=checked' : '') + '>';
	ele += '<span class="weui-icon-checked"></span>';
	ele += '</div>';
	ele += '</label>';
	return ele;
}*/

var nowElemt;

var __getdata_procom = {},
	__getdata_proget = {};

function __complete_proget(res, unkn) {
	$.hideLoading();
	if(res.status == 200) {
		if(unkn == 'wsproject') {
			if(res.data.company != '') {
				$('#btn-isreg').click();
				$('#ipt-pm-company').val(res.data.company);
			}
			if(res.data.team != '') {
				$('#ipt-pm-team').children('[value=' + res.data.team + ']').prop('selected', 'selected');
			}
			if(res.data.members != '') {
				analysis(res.data.members);
			}
			if(res.data.bp != '') {
				var bp_name = res.data.bp;
				//bp_name != '' ? bp_name = bp_name.substring(bp_name.lastIndexOf('/')+1, bp_name.length) : '';
				bp_name = bp_name != '' ? '已上传商业计划书' : '未上传商业计划书';
				$('#btn-selbp').find('.value-text').html(bp_name);
				$('#btn-selbp').attr('data-uri', res.data.bp);
			}
			data_bp = res.data.bp;
		} else if(unkn == 'editproject') {
			editProject(res.data);
		}
	} else {
		$.toptip(res.error, 'error');
	}
}

function analysis(members) {
	var m = JSON.parse(members);
	var ele = '';
	for(var i in m) {
		var ms = JSON.parse(m[i]);
		ele += '<a class="weui-cell weui-cell_access" href="javascript:;" layout-mark="btn-action-sheet">';
		ele += '<div class="weui-cell__bd">';
		ele += '<p>' + ms.name + '</p>';
		ele += '<textarea style="display:none;" >' + m[i] + '</textarea>';
		ele += '</div>';
		ele += '<div class="weui-cell__ft"></div>';
		ele += '</a>';
	}
	$('#people-list').html(ele);
}

function submitPerfectProject(jude) {
	if($('#btn-isreg').prop('checked')) __getdata_procom['company'] = $('#ipt-pm-company').val();
	else __getdata_procom['company'] = '', $('#ipt-pm-company').val('');
	__getdata_procom['team'] = $('#ipt-pm-team').val();
	var arr = [];
	$('#people-list').find('textarea').each(function(index) {
		arr.push($(this).val());
	});
	__getdata_procom['members'] = JSON.stringify(arr);
	__getdata_procom['bp'] = data_bp || '';
	$.showLoading();
	factory.request('_project_complete', jude);
}

function __complete_procom(res, unkn) {
	$.hideLoading();
	if(res.status == 201) {
		if(unkn) {
			$.toast("编辑成功", 960);
			setTimeout(function() {
				window.location.href = '/mobile/chain/fund';
			}, 800);
		} else {

		}
	} else {
		$.toptip(res.error, 'error');
	}
}

function addPeople() {
	var cmd = $(this).attr('data-cmd');
	var data_opt = {
		'name': $('#ipt-p-name').val()
	};
	var info_opt = {};
	$('#people-info').find('a').each(function(index) {
		var that = $(this);
		info_opt[that.attr('data-name')] = that.find('.value-text').html();
	});
	data_opt['info'] = JSON.stringify(info_opt);
	if(cmd == 'edit') {
		nowElemt.find('p').html(data_opt['name']);
		nowElemt.find('textarea').val(JSON.stringify(data_opt));
	} else {
		var ele = '';
		ele += '<a class="weui-cell weui-cell_access" href="javascript:;" layout-mark="btn-action-sheet">';
		ele += '<div class="weui-cell__bd">';
		ele += '<p>' + data_opt['name'] + '</p>';
		ele += '<textarea style="display:none;" >' + JSON.stringify(data_opt) + '</textarea>';
		ele += '</div>';
		ele += '<div class="weui-cell__ft"></div>';
		ele += '</a>';
		$('#people-list').append(ele);
	}
	submitPerfectProject(false);
	resPeople();
}

function resPeople() {
	$('#ipt-p-name').val('');
	$('#people-info').find('.value-text').html('');
	$('#btn-addpeople').attr('data-cmd', 'add');
	$.closePopup();
}

var __getdata_procre = {},
	__getdata_proedit = {};

function submitCreateProject() {
	var data_opt = {};
	$('[id*=ipt-pc]').each(function(index) {
		var that = $(this),
			name_arr = that.attr('id'),
			name = name_arr.split('-')[2];
		data_opt[name] = that.val();
	});
	var arr = [];
	for(var i in atlasopt) {
		arr.push(atlasopt[i]);
	}
	data_opt['atlas'] = JSON.stringify(arr);
	$.showLoading();
	if(jude_editpro) {
		__getdata_proedit = tool.optionExtend(data_opt, __getdata_proedit);
		factory.request('_project_edit');
	} else {
		__getdata_procre = data_opt;
		factory.request('_project_create');
	}
}

function __complete_procre(res) {
	$.hideLoading();
	if(res.status == 201) {
		checkLocation('finish');
	} else {
		$.toptip(res.error, 'error');
	}
}

function __complete_proedit(res) {
	$.hideLoading();
	if(res.status == 201) {
		$.toast("操作成功", 960);
		setTimeout(function() {
			window.location.href = '/mobile/chain/fund';
		}, 800);
	} else {
		$.toptip(res.error, 'error');
	}
}

var data_bp = '';

var __ulogo = {
	'imgelem': function() {
		return document.getElementById('img-pc-logo');
	},
	'process': function(base64) {

	},
	'complete': function(res) {
		if(res.status == 201) {
			$('#ipt-pc-logo').val(res.data.uri);
		} else {
			$.toptip(res.error, 'error');
		}
	}
}

var __getdata_bpupload = {};

var __ubp = {
	'get': function(obj, name) {
		//$('#btn-selbp').find('.value-text').html(name);
		__getdata_bpupload['title'] = name;
	},
	'onload': function(res) {
		if(res.status == 201) {
			data_bp = res.data.uri;

			var bp_name = res.data.uri;
			//bp_name != '' ? bp_name = bp_name.substring(bp_name.lastIndexOf('/')+1, bp_name.length) : '';
			bp_name = '商业计划书上传成功';
			$('#btn-selbp').find('.value-text').html(bp_name);
			$('#btn-selbp').attr('data-uri', res.data.uri);

			$.showLoading();
			__getdata_bpupload['bp_uri'] = res.data.uri;
			factory.request('_bp_upload');
		} else {
			$.toptip(res.error, 'error');
		}
	},
	'onerror': function(res) {
		$.toptip('上传失败，请检测图片和网络', 'error');
	}
}

function __complete_bpupload(res) {
	$.hideLoading();
	if(res.status == 201) {
		/*var data_opt = {
			'id': res.data.create_time,
			'title': res.data.title,
			'bp_uri': res.data.bp_uri,
			'checked': 'checked'
		}
		var ele = createBpvNode(data_opt);
		$('#bpvlist').append(ele);*/

	} else {
		$.toptip(res.error, 'error');
	}
}

var atlasopt = {},
	_atlasid;

var __uatlas = {
	'imgelem': function() {
		return document.createElement('img');
	},
	'process': function(base64) {
		_atlasid = new Date().getTime();
		atlasopt[_atlasid] = base64;
		var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)" data-id="' + _atlasid + '"></li>';
		$("#uploaderFiles").append($(tmpl.replace('#url#', base64)));
	},
	'complete': function(res) {
		if(res.status == 201) {
			atlasopt[_atlasid] = res.data.uri;
		} else {
			$.toptip(res.error, 'error');
		}
	}
}

function editProject(data) {
	//console.dir(data);
	$.showLoading();
	$('[id*=ipt-pc]').each(function(index) {
		var that = $(this),
			name_arr = that.attr('id'),
			name = name_arr.split('-')[2];
		that.val(data[name]);
	});
	$('#img-pc-logo').attr('src', data.logo);
	var atlas_arr = JSON.parse(data.atlas);
	for(var i in atlas_arr) {
		_atlasid = new Date().getTime();
		atlasopt[_atlasid] = atlas_arr[i];
		var tmpl = '<li class="weui-uploader__file" style="background-image:url(' + atlas_arr[i] + ')" data-id="' + _atlasid + '"></li>';
		$("#uploaderFiles").append(tmpl);
	}
	thin.imports('/public/configure/conf.opts.js', function() {
		$('[id*=btn-pc]').each(function(index) {
			var that = $(this),
				name_arr = that.attr('id'),
				name = name_arr.split('-')[2];
			that.find('.value-text').text(data[name]);
			__getdata_opts.name = name;
			factory.request('_common_opts', [name, data[name]]);
		});
		setTimeout(function() {
			$.hideLoading();
		}, 1200);
	});
}

var __getdata_opts = {};

function __complete_opts(res, unkn) {
	if(res.status == 200) {
		var opts = {
			title: "请选择",
			items: res.data,
			input: unkn[1],
			onClose: function(res) {
				$('#btn-pc-' + unkn[0]).find('.value-text').html(res.data.titles);
				$('#ipt-pc-' + unkn[0]).val(res.data.titles);
			}
		};
		$('#btn-pc-' + unkn[0]).on('click', function(e) {
			var e = e || window.event;
			e.stopPropagation();
			e.preventDefault();
			$(this).select('open');
			return false;
		}).select(opts);
	} else {
		// nothing
	}
}

var jude_basics = false,
	jude_perfect = false,
	jude_editpro = false,
	jude_selbp = false;

// 路由
function checkLocationCallback(hash) {
	if(hash == 'perfect') {
		var proid = tool.GetQueryString('proid');
		if(proid) {
			if(!jude_perfect) {
				$.showLoading();
				__getdata_procom['project_id'] = __getdata_proget['project_id'] = proid;
				__getdata_proget['model'] = 0;
				factory.request('_project_get', 'wsproject');
				thin.imports('/public/configure/conf.bp.js');
				jude_perfect = true;
			}
		}
	}

	if(hash == 'basics') {
		if(!jude_basics) {
			$.showLoading();
			var proid = tool.GetQueryString('proid');
			if(proid) {
				checkLocationTitle('编辑项目');
				__getdata_proedit['project_id'] = __getdata_proget['project_id'] = proid;
				__getdata_proget['model'] = 0;
				factory.request('_project_get', 'editproject');
				jude_editpro = true;
			} else {
				checkLocationTitle('创建项目');
				thin.imports('/public/configure/conf.opts.js', function() {
					__getdata_opts.name = 'stage';
					factory.request('_common_opts', ['stage', '']);
					__getdata_opts.name = 'round';
					factory.request('_common_opts', ['round', '']);
					__getdata_opts.name = 'industry';
					factory.request('_common_opts', ['industry', '']);
					__getdata_opts.name = 'city';
					factory.request('_common_opts', ['city', '']);
					setTimeout(function() {
						$.hideLoading();
					}, 1200);
				});
			}
			jude_basics = true;
		}
	}
}